package app

import (
	"fmt"
	"io"
	// "net/http"
	"os"
	"path/filepath"
	"time"

	"github.com/go-apibox/api"
	"github.com/go-apibox/filter"
	// "github.com/tealeg/xlsx"
)

func ActionAttachmentUpload(c *api.Context) interface{} {
	r := c.Request()
	r.ParseMultipartForm(1024 * 32)
	mForm := r.MultipartForm
	if mForm == nil || mForm.File == nil {
		return c.Error.New(api.ErrorInvalidParam, "file not find")
	}

	for k, _ := range mForm.File {
		// // k is the key of file part
		f, h, err := r.FormFile(k)
		if err != nil {

			app.logger.Error(err)
			continue
		}
		tmpName := fmt.Sprintf("%s/%s_%d.xlsx", app.config.DataDir, h.Filename, time.Now().UnixMicro())
		fd, err := os.Create(tmpName)
		if err != nil {
			app.logger.Error(err)
			continue
			// return c.Error.New(api.ErrorInternalError, "file")

		}
		io.Copy(fd, f)
		fd.Close()
		f.Close()

		_, name := filepath.Split(tmpName)
		return map[string]string{"AttachmeentId": name}
	}
	return c.Error.New(api.ErrorInternalError, "not find file")
}
func ActionAttachmentDownload(c *api.Context) interface{} {
	params := c.NewParams()
	params.Add("AttPath", filter.EmptyToNil(), filter.Required(), filter.String())
	if apiErr := params.Parse(); apiErr != nil {
		return apiErr
	}

	name := params.GetString("AttPath")

	// build addr
	// /path/id_size.png
	aPath := filepath.Join(app.config.DataDir, name)

	_, err := os.Stat(aPath)
	if err != nil {
		app.logger.Error(err)
		return c.Error.New(api.ErrorInternalError, err.Error())
	}

	fd, err := os.Open(aPath)
	if err != nil {
		app.logger.Error(err)
		return c.Error.New(api.ErrorInternalError, err.Error())
	}
	defer fd.Close()
	c.CloseResponse()

	c.Response().Header().Add("Access-Control-Allow-Origin", "*")
	// c.Response().Header().Add("Content-Type", "image/png")
	c.Response().Header().Add("Content-Disposition", "attachment;filename="+name)
	c.Response().WriteHeader(200)

	io.Copy(c.Response(), fd)

	return nil
}
